package com.timer;

import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 设置每周二的15：38分执行任务
 */
public class CalendarScheduled implements Runnable{
    String jobName;
    int count;
    ScheduledExecutorService scheduledExecutorService;

    public CalendarScheduled(String job) {
        this.jobName = job;
        this.count = 1;
        this.scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
    }

    @Override
    public void run() {
        if(count>=5){
            System.out.println(String.format("本周:%s,%s次，下周再来",jobName,count));
            scheduledExecutorService.shutdown();

        }
        System.out.println(String.format("执行任务:%s,开始时间:%s,操了%s次",jobName,new Date(),count));
        count++;
    }

    /**
     * 获取指定时间与当前时间时间差
     * @param curCalendar
     * @param executorCalendar
     * @return
     */
    public Long getEarlyDelayDate(Calendar curCalendar, Calendar executorCalendar){
        //中国周2是在国外是周3
        int day = curCalendar.get(Calendar.DAY_OF_WEEK);
        //从天开始比起，然后对比小时，与分钟
        int hour = curCalendar.get(Calendar.HOUR_OF_DAY);
        int minite = curCalendar.get(Calendar.MINUTE);

        //大于周二
        if(day>3){
            //设置为下周
            executorCalendar.set(Calendar.WEEK_OF_MONTH,curCalendar.get(Calendar.WEEK_OF_MONTH)+1);
        }

        //等于周二
        if(day==3){
            //对比小时
            if (hour>15){
                //设置为下周
                executorCalendar.set(Calendar.WEEK_OF_MONTH,curCalendar.get(Calendar.WEEK_OF_MONTH)+1);
            }
            if(hour==15){
                //对比分钟
                if(minite>38){
                    //设置为下周
                    executorCalendar.set(Calendar.WEEK_OF_MONTH,curCalendar.get(Calendar.WEEK_OF_MONTH)+1);
                }
            }
        }
        System.out.println(executorCalendar.getTime());
        System.out.println(curCalendar.getTime());

        return executorCalendar.getTimeInMillis() - curCalendar.getTimeInMillis();
    }

    public static void main(String[] args) {


    //    设置每周二的15：38分执行任务 public static void main(String[] args) {
        //当前时间
        Calendar curCalendar = Calendar.getInstance();
        //指定时间
        Calendar setCalendar = Calendar.getInstance();
        setCalendar.set(Calendar.DAY_OF_WEEK,3);
        setCalendar.set(Calendar.HOUR_OF_DAY,15);
        setCalendar.set(Calendar.MINUTE,19);

        CalendarScheduled calendarScheduled = new CalendarScheduled("操你妈");
        long delay = calendarScheduled.getEarlyDelayDate(curCalendar,setCalendar);

        calendarScheduled.scheduledExecutorService.scheduleAtFixedRate(calendarScheduled,delay,60*1000*60*24*7, TimeUnit.MILLISECONDS);



    }

}
